/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PesquisaManutencaoPedidoView.java
 *
 * Created on 24/06/2011, 21:31:18
 */

package br.com.comprasPublicas.view.pesquisa;

import br.com.comprasPublicas.entity.Pedido;
import br.com.comprasPublicas.util.FormatadoresUtil;
import br.com.comprasPublicas.util.HibernateUtil;
import br.com.comprasPublicas.view.cadastro.ManutencaoPedidoView;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;


/**
 *
 * @author helsen
 */
public class PesquisaManutencaoPedidoView extends javax.swing.JDialog {

    /** Creates new form PesquisaManutencaoPedidoView */
    public PesquisaManutencaoPedidoView(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        preencher_tblPedidos();
        lista = listar_pedido();
        preencher_pedido();
        tblPedidos.setSelectionMode(0);
        
        preencher_datas();

        //Método utilizado para centralizar o JFrame na tela
        Dimension tela = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((tela.width - this.getSize().width) / 2, (tela.height - this.getSize().height) / 2);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnSelecionar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        txtPedido = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtDepartamento = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtSecao = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblPedidos = new javax.swing.JTable();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        btnPesquisar = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();
        ftxtDataInicial = new javax.swing.JFormattedTextField();
        ftxtDataFinal = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(br.com.comprasPublicas.compraspublicas.ComprasPublicasApp.class).getContext().getResourceMap(PesquisaManutencaoPedidoView.class);
        btnSelecionar.setFont(resourceMap.getFont("btnSelecionar.font")); // NOI18N
        btnSelecionar.setMnemonic('s');
        btnSelecionar.setText(resourceMap.getString("btnSelecionar.text")); // NOI18N
        btnSelecionar.setName("btnSelecionar"); // NOI18N
        btnSelecionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelecionarActionPerformed(evt);
            }
        });

        jLabel1.setName("jLabel1"); // NOI18N

        txtPedido.setName("txtPedido"); // NOI18N

        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setName("jLabel4"); // NOI18N

        txtDepartamento.setName("txtDepartamento"); // NOI18N

        jLabel5.setName("jLabel5"); // NOI18N

        txtSecao.setName("txtSecao"); // NOI18N

        jLabel6.setName("jLabel6"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tblPedidos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Pedido", "Data", "Objeto", "Seção", "Departamento"
            }
        ));
        tblPedidos.setName("tblPedidos"); // NOI18N
        tblPedidos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jScrollPane1.setViewportView(tblPedidos);

        jLabel7.setFont(resourceMap.getFont("jLabel10.font")); // NOI18N
        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        jLabel8.setFont(resourceMap.getFont("jLabel10.font")); // NOI18N
        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        jLabel9.setFont(resourceMap.getFont("jLabel10.font")); // NOI18N
        jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
        jLabel9.setName("jLabel9"); // NOI18N

        jLabel10.setFont(resourceMap.getFont("jLabel10.font")); // NOI18N
        jLabel10.setText(resourceMap.getString("jLabel10.text")); // NOI18N
        jLabel10.setName("jLabel10"); // NOI18N

        jLabel11.setFont(resourceMap.getFont("jLabel10.font")); // NOI18N
        jLabel11.setText(resourceMap.getString("jLabel11.text")); // NOI18N
        jLabel11.setName("jLabel11"); // NOI18N

        btnPesquisar.setFont(resourceMap.getFont("btnPesquisar.font")); // NOI18N
        btnPesquisar.setMnemonic('p');
        btnPesquisar.setText(resourceMap.getString("btnPesquisar.text")); // NOI18N
        btnPesquisar.setName("btnPesquisar"); // NOI18N
        btnPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPesquisarActionPerformed(evt);
            }
        });

        jLabel12.setFont(resourceMap.getFont("jLabel12.font")); // NOI18N
        jLabel12.setText(resourceMap.getString("jLabel12.text")); // NOI18N
        jLabel12.setName("jLabel12"); // NOI18N

        ftxtDataInicial.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM))));
        ftxtDataInicial.setText(resourceMap.getString("ftxtDataInicial.text")); // NOI18N
        ftxtDataInicial.setName("ftxtDataInicial"); // NOI18N

        ftxtDataFinal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM))));
        ftxtDataFinal.setText(resourceMap.getString("ftxtDataFinal.text")); // NOI18N
        ftxtDataFinal.setName("ftxtDataFinal"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addGap(10, 10, 10)
                        .addComponent(jLabel12)
                        .addGap(704, 704, 704)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(68, 68, 68)
                                .addComponent(jLabel3)
                                .addGap(68, 68, 68)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel5))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPedido, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ftxtDataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel9)
                        .addGap(18, 18, 18)
                        .addComponent(ftxtDataFinal, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(24, 24, 24)
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtSecao, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(20, 20, 20)
                        .addComponent(jLabel11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnPesquisar))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1141, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(1030, Short.MAX_VALUE)
                        .addComponent(btnSelecionar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(jLabel6))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel12)))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(jLabel10)
                            .addComponent(jLabel11)
                            .addComponent(txtPedido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel8)
                            .addComponent(txtSecao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(ftxtDataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel9)
                            .addComponent(ftxtDataFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnPesquisar)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3)
                        .addComponent(jLabel4)
                        .addComponent(jLabel5)))
                .addGap(11, 11, 11)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSelecionar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSelecionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionarActionPerformed
        if (tblPedidos.getSelectedRow()==-1){
            JOptionPane.showMessageDialog(null, "Nenhum Pedido Selecionado");
        } else{
            String selecao = tblPedidos.getModel().getValueAt(tblPedidos.getSelectedRow(), 0).toString();
            ManutencaoPedidoView.ped = selecao;
            limpa_objetos();
            dispose();
        }
}//GEN-LAST:event_btnSelecionarActionPerformed

    private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed
        if (ftxtDataInicial.getText().equals("")) preencher_datas();
        lista = listar_parametros();
        preencher_pedido();
    }//GEN-LAST:event_btnPesquisarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PesquisaManutencaoPedidoView dialog = new PesquisaManutencaoPedidoView(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnPesquisar;
    private javax.swing.JButton btnSelecionar;
    private javax.swing.JFormattedTextField ftxtDataFinal;
    private javax.swing.JFormattedTextField ftxtDataInicial;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblPedidos;
    private javax.swing.JTextField txtDepartamento;
    private javax.swing.JTextField txtPedido;
    private javax.swing.JTextField txtSecao;
    // End of variables declaration//GEN-END:variables

    public void preencher_tblPedidos()
    {
        try
        {
            tblPedidos.getColumnModel().getColumn(0).setPreferredWidth(20);
            tblPedidos.getColumnModel().getColumn(1).setPreferredWidth(20);
            tblPedidos.getColumnModel().getColumn(2).setPreferredWidth(500);
            tblPedidos.getColumnModel().getColumn(3).setPreferredWidth(50);
            tblPedidos.getColumnModel().getColumn(4).setPreferredWidth(50);

            DefaultTableModel modelo_tbl = (DefaultTableModel) tblPedidos.getModel();
            modelo_tbl.setNumRows(0);

        }
        catch(Exception erro)
        {
            JOptionPane.showMessageDialog(null, "Não foi possível preencher tabela "+erro);
        }
    }

    private void preencher_pedido() {
        int tam_lista = lista.size();
        
        DefaultTableModel modelo_tbl = (DefaultTableModel) tblPedidos.getModel();
        modelo_tbl.setNumRows(0);

        pedido = new Pedido();
        for (int i=0; i<tam_lista; i++ ){
            pedido = (Pedido) lista.get(i);
            //alterando o formato da data do pedido para ex.31/12/2011
            Date dataPedido = pedido.getData_pedido();
            String formato = "dd/MM/yyyy";
            SimpleDateFormat formatter = new SimpleDateFormat(formato);
            String dataTabela = formatter.format(dataPedido);
            modelo_tbl.addRow(new Object[]{pedido.getId_pedido(),
                                           dataTabela,
                                           pedido.getObjeto_compra(),
                                           pedido.getSecao().getSecao(),
                                           pedido.getSecao().getDepartamento().getDepartamento()
                                          } );
        }
        lista = null;

    }
    private List listar_pedido(){
        Session sessao = HibernateUtil.getSessao();
        Transaction transacao = sessao.beginTransaction();

        Criteria c = sessao.createCriteria(Pedido.class);

        List listaBusca = c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

        transacao.commit();
        sessao.close();
        
        return listaBusca;
    }

    //Verificando os parâmetros preenchidos e restrigindo a busca
    private List listar_parametros() {
        Session sessao = HibernateUtil.getSessao();
        Transaction transacao = sessao.beginTransaction();

        Criteria c = sessao.createCriteria(Pedido.class).createAlias("secao", "s").createAlias("secao.departamento", "d");

        //Restrição pelo pedido
        if (!txtPedido.getText().equals("")){
            int pedidoBusca = Integer.parseInt(txtPedido.getText());
            c.add(Restrictions.eq("id_pedido", pedidoBusca));
        }
        

        //Restrição pelas datas
        Date dataInicial = Calendar.getInstance().getTime();
        dataInicial = FormatadoresUtil.data2Banco(ftxtDataInicial.getText());
        Date dataFinal = Calendar.getInstance().getTime();
        dataFinal = FormatadoresUtil.data2Banco(ftxtDataFinal.getText());
        c.add(Restrictions.between("data_pedido", dataInicial, dataFinal));

        //Restrição pela seção
        if (!txtSecao.getText().equals("")){
            int idSecao = Integer.parseInt(txtSecao.getText());
            c.add(Restrictions.eq("s.id_secao", idSecao));
        }

        //Restrição pelo departamento
        if (!txtDepartamento.getText().equals("")) c.add(Restrictions.eq("d.id_departamento", Integer.parseInt(txtDepartamento.getText())));

        List listaBusca = c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

        transacao.commit();
        sessao.close();
        return listaBusca;
    }

    private void preencher_datas() {
        //DataInicial pré-preenchida primeiro dia do ano
        ftxtDataInicial.setText("01/01/2011");

        //DataFinal pré-preenchida data de hoje
        Date hoje = new Date(System.currentTimeMillis());
        String formato = "dd/MM/yyyy";
        SimpleDateFormat formatter = new SimpleDateFormat(formato);
        String dataHoje = formatter.format(hoje);
        ftxtDataFinal.setText(dataHoje);
    }

    
    private Pedido pedido;
    private List lista;

    private void limpa_objetos() {
        pedido = null;
        lista = null;
    }




}
